﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using Prism.Games.GalEngine.Scripts;
using Prism.Games.GalEngine.Scripts.Parser;

namespace Prism.Games.GalEngine.Scripts.Parser.GameRunner
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var file = GameFrameLibrary.Strings.WindowConfig;
            if (File.Exists(file))
                this.WindowConfig = System.Xaml.XamlServices.Load(file) as WindowConfig;

            //Load Script
            ContentsRoot script;
            var bf = new BinaryFormatter();
            using (var fs = new FileStream(GameFrameLibrary.Strings.Scripts, FileMode.Open))
            {
                script = bf.Deserialize(fs) as ContentsRoot;
            }

            if (script != null)
            {
                this.Parser = new ScriptParser(script);

                if (this.WindowConfig != null)
                {
                    this.XMainWindow = new MainWindow(this.Parser, this.WindowConfig);


                    if (this.WindowConfig.IsFullScreen)
                    {
                        this.XMainWindow.FullScreen();
                    }
                    else
                    {
                        this.XMainWindow.ResumeWindowMode();
                    }
                    this.XMainWindow.Show();
                }
                else
                {
                    this.WindowConfig = new WindowConfig()
                    {
                        NativeHeight = script.NativeResolutionHeight,
                        NativeWidth = script.NativeResolutionWidth,
                        ZoomHeight = script.NativeResolutionHeight,
                        ZoomWidth = script.NativeResolutionWidth,
                        Name = script.GameName
                    };

                    this.XMainWindow = new MainWindow(this.Parser, this.WindowConfig);

                    this.XMainWindow.ResumeWindowMode();
                    this.XMainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    this.XMainWindow.Show();
                }

                this.Parser.GraphicBase.SetWindowConfig(this.WindowConfig);
                this.Parser.GraphicBase.GameWindow = this.XMainWindow;
                this.Parser.Initialization();
            }

            this.MainWindow = this.XMainWindow;
        }

        private ScriptParser Parser;

        private WindowConfig WindowConfig;

        private MainWindow XMainWindow;
    }
}
